#pragma once
#include <string>
#include <jsoncpp/json/json.h>

namespace PackManageModule
{
    const static std::string sep = "\r\n";

    struct PackManage
    {
        // 封包
        static bool Encode(std::string &message, std::string *package)
        {
            if (message.size() == 0)
                return false;
            // 转成17\r\nmessage\r\n的格式
            *package = std::to_string(message.size()) + sep + message + sep;
            return true;
        }
        // 解包
        static bool Decode(std::string &package, std::string *content)
        {
            auto pos = package.find(sep);
            if (pos == std::string::npos)
                return false;
            std::string content_length_str = package.substr(0, pos);
            int content_length = std::stoi(content_length_str);
            int full_length = content_length_str.size() + content_length + 2 * sep.size();

            if (package.size() < full_length)
                return false;

            *content = package.substr(pos + sep.size(), content_length);

            // package erase
            package.erase(0, full_length);
            return true;
        }
    };
}
